package com.fortune.rainshineservice.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @program: rainShine
 * @description:
 * @author: tangyn
 * @create: 2019-05-17
 **/
@Service
public class RedisLock {

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String LOCK_PREFIX = "redis_lock";
    public static final int LOCK_EXPIRE = 1000 * 60 * 60 * 1; // ms


    /**
     * redis 加锁
     * @param key
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public boolean lock(String key) {
        String lock = LOCK_PREFIX + key;
        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
            long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
            Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
            if (acquire) {
                return true;
            } else {
                byte[] value = connection.get(lock.getBytes());
                if (Objects.nonNull(value) && value.length > 0) {
                    long expireTime = Long.parseLong(new String(value));
                    if (expireTime < System.currentTimeMillis()) {
                        // 如果锁已经过期
                        byte[] oldValue = connection.getSet(lock.getBytes(),
                                String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
                        // 防止死锁
                        return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
                    }
                }
            }
            return false;
        });

    }


    /**
     * redis 解锁
     * @param key
     */
    @SuppressWarnings("unchecked")
    void unLock(String key) {
        String lock = LOCK_PREFIX + key;
        redisTemplate.delete(lock);
    }

}
